//
//  ProvinceCityController.swift
//  SlaughterClient
//
//  Created by Ken on 2020/2/14.
//  Copyright © 2020 zwb. All rights reserved.
//  网络获取的省市区控件

import UIKit
import ObjectMapper
struct ProCitResult: Mappable {
    
    var id_key: String?
    var canton_nm: String?
    
    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        
        id_key <- (map["id_key"],StringTransform())
        canton_nm <- map["canton_nm"]
    }
    
}
var NetProvinArr:[ProCitResult] = []//省  数组
var NetCityDic:[String:[ProCitResult]] = [:]// 市   字典
var NetDictDic:[String:[ProCitResult]] = [:]// 区   字典
  
class ProvinceCityNetVC: UIViewController {
   
    var table1:UITableView!
    var table2:UITableView!
    var table3:UITableView!
    
    var province:ProCitResult?
    var city:ProCitResult?
    var district:ProCitResult?
    
    var cityArr = [ProCitResult]()
    var districtArr = [ProCitResult]()
      var citySelectClosure:((ProCitResult)->())?
    var tripleSelectClosure:((ProCitResult?,ProCitResult?,ProCitResult?)->())?
 
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "城市选择"
        
        let leftBtn = UIButton.creat4Item(title: "返回") { _ in
           self.closeAction()
       }
       let left = UIBarButtonItem(customView: leftBtn)
       self.navigationItem.leftBarButtonItem = left
        let rightBtn = UIButton.creat4Item(title: "确定") { _ in
            if let clo = self.tripleSelectClosure {
                clo(self.province,self.city,self.district)
            }
            self.closeAction()
             
       }
       let right = UIBarButtonItem(customView: rightBtn)
       self.navigationItem.rightBarButtonItem = right
  
        table1 = UITableView(frame: CGRect(x:0,y: 0,width: 110,height: KSGlobal.screenH))
        table1.delegate = self
        table1.dataSource = self
         self.view.addSubview(table1)
        
        table2 = UITableView(frame: CGRect(x:111,y: 0,width: 110,height: KSGlobal.screenH))
        table2.tableFooterView = UIView()
        table2.delegate = self
        table2.dataSource = self
        self.view.addSubview(table2)
        
        
        table1.register(UITableViewCell.self, forCellReuseIdentifier: "provinceCell_1")
        table2.register(UITableViewCell.self, forCellReuseIdentifier: "cityCell_2")
        
       
            table3 = UITableView(frame: CGRect(x:222,y: 0,width: KSGlobal.screenW - 222,height: KSGlobal.screenH))
            table3.tableFooterView = UIView()
            table3.delegate = self
            table3.dataSource = self
            self.view.addSubview(table3)
            
            table3.register(UITableViewCell.self, forCellReuseIdentifier: "districtCell_3")
        
        
        getProvince { arr in
            NetProvinArr = arr
            self.province = NetProvinArr[0]
            self.table1.reloadData()
//            self.getCity(id: NetProvinArr[0].id_key.unwrap) { arrC in
//                self.cityArr = arrC
//                self.table2.reloadData()
//                self.city = self.cityArr[0]
//                self.getDict(id:  self.city!.id_key.unwrap) { arrC in
//                    self.districtArr = arrC
//                    self.district = self.districtArr[0]
//                    self.table3.reloadData()
//                }
//            }
        }
    }
    func closeAction() {
        if self.navigationController!.viewControllers.count > 1 { // 说明是push过来的
            self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: {
            })
        }
    }
}

extension ProvinceCityNetVC:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if tableView == table1 {
            return NetProvinArr.count
        } else if tableView == table2 {
            return cityArr.count
        } else {
            return districtArr.count
        }
        
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == table1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "provinceCell_1", for: indexPath)
             cell.textLabel?.text = NetProvinArr[indexPath.row].canton_nm
            if self.province?.canton_nm == NetProvinArr[indexPath.row].canton_nm {
                cell.isSelected = true
            } else {
                cell.isSelected = false
            }
            
            return cell
        } else if  tableView == table2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell_2", for: indexPath)
             cell.textLabel?.text = cityArr[indexPath.row].canton_nm
            if self.city?.canton_nm == self.cityArr[indexPath.row].canton_nm {
                cell.isSelected = true
            } else {
                cell.isSelected = false
            }
            
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "districtCell_3", for: indexPath)
             cell.textLabel?.text = districtArr[indexPath.row].canton_nm
            if self.district?.canton_nm == self.districtArr[indexPath.row].canton_nm {
                cell.isSelected = true
            } else {
                cell.isSelected = false
            }
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        

        if tableView == table1 {
          
                self.province = NetProvinArr[indexPath.row]
            self.city = nil
            self.district =  nil
                getCity(id: self.province!.id_key.unwrap, back: { arrC in
                    self.cityArr = arrC
                     self.table2.reloadData()
                })
 
            
        } else if tableView == table2 {
            
            city = self.cityArr[indexPath.row]
            self.district = nil
                 getDict(id: self.cityArr[indexPath.row].id_key.unwrap) { arrD in
                    self.districtArr = arrD
                    self.table3.reloadData()
                 }
         } else {
            district = self.districtArr[indexPath.row]
        }
    }
    
    func getProvince(back: @escaping([ProCitResult])->()) {
        if NetProvinArr.count > 0 {
            back(NetProvinArr)
        } else {
            KSNetwork.shared.doRequest(API.addr(.queryProvince(parent_id: ""))) { (data:BaseResult<ProCitResult>) in
               if data.flag == TRUE {
                   if let infosP = data.infoArrCombine {
                      back(infosP)
                    }
                }
           }
        }
     }
    func getCity(id:String,back: @escaping([ProCitResult])->()) {
        if let arr = NetCityDic[id], arr.count > 0 {
            back(arr)
        } else {
            KSNetwork.shared.doRequest(API.addr(.queryProvince(parent_id: id))) { (data:BaseResult<ProCitResult>) in
                if data.flag == TRUE {
                    if let infosC = data.infoArrCombine {
                        NetCityDic.updateValue(infosC, forKey: id)
                        back(infosC)
                      }
                 }
            }
        }
        
    }
    func getDict(id:String,back: @escaping([ProCitResult])->()) {
        if let arr = NetDictDic[id], arr.count > 0 {
            back(arr)
        } else {
            KSNetwork.shared.doRequest(API.addr(.queryProvince(parent_id: id))) { (data:BaseResult<ProCitResult>) in
                if data.flag == TRUE {
                    if let infosD = data.infoArrCombine {
                        NetDictDic.updateValue(infosD, forKey: id)
                        back(infosD)
                       }
                 }
            }
        }
    }
}
